﻿define('ui/markerList/licenseML', 
		['ui/controller/conditionController', 'ui/gis'], 
		function(conditionController, gis) {

	var licenseML = {
			
		markerList : null,	
		
		//所有的自定义饼状图marker是否渲染完成的一个标记，用cityDataLength做依据来判断
		inited: false,
		
		//后台地市数据数组
		cityData: [],
		//后台地市数据数组长度
		cityDataLength: 0,
		//地市marker数组，cityDataLength与cityData的长度相同后，自定义饼状图marker不会重新生成
		cityMarker:[],
		//所有企业点位数据，用于地图放大到一定级别后显示
		sublist:[],
		
		/**
		 * goPage方法为加载后台JSON数据的入口，获取数据后会重新渲染MarkerList，从最外层的地图饼状图开始渲染
		 */
		goPage: function(page) {
			var d = new Date();
			var expireTime;
	    	var year = conditionController.getYearCode()?conditionController.getYearCode():d.getFullYear();
	    	if(year == d.getFullYear()) {
	    		expireTime = year+'-'+ (d.getMonth()+1) +'-'+ d.getDate();
	    		expireTime = '2020-7-12';
	    	}else {
	    		expireTime = year+'-12-31';
	    	}
	        ajaxProcess({
	            url : '/pls/gis/licence/warning',
	            requestType : 'POST',
	            data : {
	            	expireTime : expireTime
	            },
	            successHandle : function(res) {
	            	//console.log(res);
	            	
	            	licenseML.clearData();
	            	
	            	var data = res.rows;
	            	var t;
	            	var d = [];
	            	for(var i=0; i<data.length; i++) {
	            		if(data[i].areaLevel=='province'){
	            			t = data[i];
	            		}else if(data[i].areaLevel=='city') {
	            			d.push(data[i]);
	            			for(var j=0; j<data[i].sublist.length;j++) {
	                    		licenseML.sublist.push(data[i].sublist[j]);
	                    	}
	            		}
	            	}
	            	//console.log('licenseML goPage：');
	            	//console.log(d);
	            	licenseML.cityData = d;
	            	licenseML.cityDataLength = d.length;
	            
	            	gis.map.setZoom(7);
	            	licenseML.renderTotal(t);
	            	licenseML.markerList.render(d);
	            }
	        });
	    },
		
	    /**
	     * load方法应该在初次加载MarkerList时调用,无论如何别多次调用，重新渲染请使用reRenderData
	     */
		load: function(){
			licenseML.clearData();
			AMapUI.loadUI(['misc/MarkerList', 'overlay/SimpleMarker', 'overlay/SimpleInfoWindow'],
			    function(MarkerList, SimpleMarker, SimpleInfoWindow) {

			    //即jQuery/Zepto
			    var $ = MarkerList.utils.$;

			    var defaultIconStyle = 'red', //默认的图标样式
			        hoverIconStyle = 'green', //鼠标hover时的样式
			        selectedIconStyle = 'purple' //选中时的图标样式
			    ;

			    var markerList = new MarkerList({
			        map: gis.map,
			        //ListElement对应的父节点或者ID
			        listContainer: "enterpriseList",
			        //选中后显示

			        //从数据中读取位置, 返回lngLat
			        getPosition: function(item) {
			            return [item.longitude, item.latitude];
			        	//return item.location;
			        },
			        //数据ID，如果不提供，默认使用数组索引，即index
			        getDataId: function(item, index) {

			            return item.id;
			        },
			        getInfoWindow: function(data, context, recycledInfoWindow) {
			        	//console.log("窗体"+data);
			        	
			        	if(!data.areaLevel){
				            
				        	var infoTitle = data.entername + ((data.warningLevel == "pastdue")?'：超期':'：未超期');
				        	var infoBody =  '<div class="poi-info-left">' +
						                    '    <h3 class="poi-title">' +
						                    '    </h3>' +
						                    '    <div class="poi-info">' +
						                    '        <p class="poi-addr">有效开始时间：'+data.stime + '</p>' +
						                    '        <p class="poi-addr">有效结束时间：'+data.etime + '</p>' +
						                    '    </div>' +
						                    '</div>' +
						                    '<div class="clear"></div>';

				            return new SimpleInfoWindow({
				                infoTitle: infoTitle,
				                infoBody:  infoBody,
				                offset: new AMap.Pixel(0, -37)
				            });
			        	}
			        	
			        	var infoTitle = data.regionname + '：许可证到期预警数量（单位：个）';
			        	var infoBody =  '<div class="poi-info-left">' +
					                    '    <h3 class="poi-title">' +
					                    '    </h3>' +
					                    '    <div class="poi-info">' +
					                    '        <p class="poi-addr">超期：'+data.pastDueNum+'&nbsp;&nbsp;&nbsp;&nbsp;1个月：'+data.onePastDueNum+'&nbsp;&nbsp;&nbsp;&nbsp;2个月：'+data.twoPastDueNum + '</p>' +
					                    '        <p class="poi-addr">3个月：'+data.threePastDueNum + '&nbsp;&nbsp;&nbsp;&nbsp;6个月：'+ data.sixPastDueNum + '&nbsp;&nbsp;&nbsp;&nbsp;6个月以上：'+data.gtSixPastDueNum + '</p>' +
					                    '    </div>' +
					                    '</div>' +
					                    '<div class="clear"></div>';
			            if (recycledInfoWindow) {

			                recycledInfoWindow.setInfoTitle(infoTitle);
			                recycledInfoWindow.setInfoBody(infoBody);

			                return recycledInfoWindow;
			            }

			            return new SimpleInfoWindow({
			                infoTitle: infoTitle,
			                infoBody:  infoBody,
			                offset: new AMap.Pixel(0, -37)
			            });
			        },
			        //构造marker用的options对象, content和title支持模板，也可以是函数，返回marker实例，或者返回options对象
			        getMarker: function(data, context, recycledMarker) {
			        	//console.log('地区级别：'+data.areaLevel);
			        	//console.log('getMarker：'+data);
			            var label = context.index+1;//String.fromCharCode('A'.charCodeAt(0) + context.index);
			            /*
			            if (recycledMarker) {
			                recycledMarker.setIconLabel(label);
			                return;
			            }
			           */
			        	
			        	if(!data.areaLevel){
				            return new SimpleMarker({
				                containerClassNames: 'my-marker',
				                iconStyle: licenseML.markerStyle(data),//defaultIconStyle,
				                iconLabel: label
				            });
			        	}
			        	
			        	if(licenseML.cityMarker && licenseML.inited) {
			        		return licenseML.cityMarker[context.index];
			        	}
			        	return licenseML.createCustomMarker(data, context.index);
			        },
			        //构造列表元素，与getMarker类似，可以是函数，返回一个dom元素，或者模板 html string
			        getListElement: function(data, context, recycledListElement) {

			            var label = context.index+1;
			            
			            
			            if(!data.areaLevel){
			            	var innerHTML = MarkerList.utils.template(
				                    '<div class="poi-info-left">' +
				                    '    <h3 class="poi-title">' +
				                    '        <%- label %>. <%- data.entername %>' + "：" +
				                    '			<% if(data.warningLevel == "pastdue") { %>' +
				                    ''				+ '超期' +
				                    '			<% } %>'+
				                    '			<% if(data.warningLevel != "pastdue") { %>' +
				                    ''				+ '未超期' +
				                    '			<% } %>'+
				                    '    </h3>' +
				                    '    <div class="poi-info">' +
				                    '        <p class="poi-addr">地址：<%- data.enteraddress %></p>' +
				                    '        <p class="poi-addr">许可证有效开始结束时间：<%- data.stime %>至<%- data.etime %></p>' +
				                    '    </div>' +
				                    '</div>' +
				                    '<div class="clear"></div>', {
				                        data: data,
				                        label: label
				                    });

				            return 	'<li class="poibox">' +
					                innerHTML +
					                '</li>';
			        	}

			            //./images/guo.png
			            var innerHTML = MarkerList.utils.template(
			                    '<div class="poi-info-left">' +
			                    '    <h3 class="poi-title">' +
			                    '        <%- label %>. <%- data.regionname %>' + '：许可证到期预警数量（单位：个）' + 
			                    '    </h3>' +
			                    '    <div class="poi-info">' +
			                    '        <p class="poi-addr">超期：<%- data.pastDueNum %>&nbsp;&nbsp;&nbsp;&nbsp;1个月：<%- data.onePastDueNum %>&nbsp;&nbsp;&nbsp;&nbsp;2个月：<%- data.twoPastDueNum %></p>' +
			                    '        <p class="poi-addr">3个月：<%- data.threePastDueNum %>&nbsp;&nbsp;&nbsp;&nbsp;6个月：<%- data.sixPastDueNum %>&nbsp;&nbsp;&nbsp;&nbsp;6个月以上：<%- data.gtSixPastDueNum %></p>' +
			                    '    </div>' +
			                    '</div>' +
			                    '<div class="clear"></div>', {
			                        data: data,
			                        label: label
			                    });

			            if (recycledListElement) {
			                recycledListElement.innerHTML = innerHTML;
			                return recycledListElement;
			            }

			            return 	'<li class="poibox">' +
				                innerHTML +
				                '</li>';
			        },
			        //列表节点上监听的事件
			        listElementEvents: ['click', 'mouseenter', 'mouseleave'],
			        //marker上监听的事件
			        markerEvents: ['click', 'mouseover', 'mouseout'],
			        //makeSelectedEvents:false,
			        selectedClassNames: 'selected',
			        autoSetFitView: false
			    });

			    //window.markerList = markerList;
			    licenseML.markerList = markerList;

			    licenseML.goPage(1);
			    
			    AMap.event.addListener(gis.map, 'zoomend', licenseML._onZoomEnd);

			    markerList.on('selectedChanged', function(event, info) {

			        if (info.selected) {

			            //console.log(info);
			            
			            if (info.selected.marker) {
			                //更新为选中样式
			                //info.selected.marker.setIconStyle(selectedIconStyle);
			            }

			            //选中并非由列表节点上的事件触发，将关联的列表节点移动到视野内
			            if (!info.sourceEventInfo.isListElementEvent) {

			                if (info.selected.listElement) {
			                    scrollListElementIntoView($(info.selected.listElement));
			                }
			            }
			        }

			        if (info.unSelected && info.unSelected.marker) {
			            //更新为默认样式
			            //info.unSelected.marker.setIconStyle(defaultIconStyle);
			        }
			    });

			    markerList.on('listElementMouseenter markerMouseover', function(event, record) {

			        if (record && record.marker) {

			            forcusMarker(record.marker);

			            //this.openInfoWindowOnRecord(record);

			            //非选中的id
			            if (!this.isSelectedDataId(record.id)) {
			                //设置为hover样式
			                //record.marker.setIconStyle(hoverIconStyle);
			                //this.closeInfoWindow();
			            }
			        }
			    });

			    markerList.on('listElementMouseleave markerMouseout', function(event, record) {

			        if (record && record.marker) {

			            if (!this.isSelectedDataId(record.id)) {
			                //恢复默认样式
			                //record.marker.setIconStyle(defaultIconStyle);
			            }
			        }
			    });

			    //数据输出完成
			    markerList.on('renderComplete', function(event, records) {

			    });

			    // markerList.on('*', function(type, event, res) {
			    //     console.log(type, event, res);
			    // });

			    function forcusMarker(marker) {
			        marker.setTop(true);

			        //不在地图视野内
			        if (!(gis.map.getBounds().contains(marker.getPosition()))) {

			            //移动到中心
			        	gis.map.setCenter(marker.getPosition());
			        }
			    }

			    function isElementInViewport(el) {
			        var rect = el.getBoundingClientRect();

			        return (
			            rect.top >= 0 &&
			            rect.left >= 0 &&
			            rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
			            rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
			        );
			    }

			    function scrollListElementIntoView($listEle) {

			        if (!isElementInViewport($listEle.get(0))) {
			            $('#panel').scrollTop(($listEle.offset().top - $listEle.parent().offset().top)+'px');
			            //console.log($listEle.offset().top - $listEle.parent().offset().top);
			        }

			        //闪动一下
			        $listEle
			            .one('webkitAnimationEnd oanimationend msAnimationEnd animationend',
			                function(e) {
			                    $(this).removeClass('flash animated');
			                }).addClass('flash animated');
			    }
			});
		},
		
		/**
		 * 重新渲染MarkerList
		 */
		reRenderData:function(data){
			licenseML.goPage(1);
		},
		
		/**
		 * 1、销毁MarkerList
		 * LMarkerList下的数据cityData、cityMarker、sublist只是简单重置，已使用的内存不一定得到释放
		 * 2、全省的许可证数量汇总面板，被清空
		 */
		clearData: function(){
			console.log('销毁LMarkerList：'+licenseML.markerList);
			if(licenseML.markerList && licenseML.markerList.getData() && licenseML.markerList.getData().length>0) {
				licenseML.markerList.clearData();
				
				licenseML.inited = false;
				licenseML.cityData = [];
				licenseML.cityDataLength = 0;
				licenseML.cityMarker = [];
				licenseML.sublist = [];
			}
			if($('#warmTotal').length>0) {
				$('#totalLicenseContent').html("");
			}
		},
		
		/**
		 * 许可证到期预警汇总
		 */
		renderTotal:function(data){
			AMapUI.loadUI(['misc/MarkerList'], function(MarkerList) {
				var totalList = '<ul id="warmTotal">'+
									'<li>'+
									'<div class=""><span style="color:#613762">超期：<a href="#" style="color:#613762">'+data.pastDueNum+'</a></span></div>'+
									'</li>'+
									'<li>'+
										'<div class=""><span style="color:#B62C2F">1个月内：<a href="#" style="color:#B62C2F">'+data.onePastDueNum+'</a></span></div>'+
									'</li>'+
									'<li><div class=""><span style="color:#EF2D06">2个月内：<a href="#" style="color:#EF2D06">'+data.twoPastDueNum+'</a></span></div></li>'+
									'<li><div class=""><span style="color:#FF7371">3个月内：<a href="#" style="color:#FF7371">'+data.threePastDueNum+'</a></span></div></li>'+
									'<li>'+
										'<div class=""><span style="color:#FF9022">6个月内：<a href="#" style="color:#FF9022">'+data.sixPastDueNum+'</a></span></div>'+
									'</li>'+
									'<li>'+
										'<div class=""><span style="color:#59B136">6个月以上：<a href="#" style="color:#59B136">'+data.gtSixPastDueNum+'</a></span></div>'+
									'</li>'+
								'</ul>';
				var html = MarkerList.utils.template(totalList, {data: data}); 
				$("#totalLicenseContent").show();
				$("#totalLicenseContent").html("").html(html); 
			});
		},
		
		/**
		 * 点位颜色样式：根据预警时间段的不同
		 */
		markerStyle : function(data) {
		    var r = 'green';
	        if(data.warningLevel=='pastdue') {
	        	r = 'purple';
	        }else if(data.warningLevel=='onepastdue'){
	        	r = 'darkred';
	        }else if(data.warningLevel=='twopastdue'){
	        	r = 'red';
	        }else if(data.warningLevel=='threepastdue'){
	        	r = 'salmon';
	        }else if(data.warningLevel=='sixpastdue'){
	        	r = 'orange';
	        }else if(data.warningLevel=='gtsixpastdue'){
	        	r = 'green';
	        }
		    return r;
		},
		
		 /**
	     * 地图上的收缩响应事件，重新渲染饼状图，清掉企业点位
	     */
		_onZoomEnd : function(e) {
	        if (gis.map.getZoom() < 8) {
	        	//这里要检查一下地图是否已经存在数据了，存在不应该重新渲染了
	        	licenseML.markerList.render(licenseML.cityData);
	        }else{
	        	licenseML.markerList.render(licenseML.sublist);
	        }
	    },
	    
	    /**
	     * 地图上的饼状图点击响应事件，渲染该地市下面的企业点位信息，清掉饼状图
	     */
	    _onClick : function(e) {
	    	console.log(e);
	    	console.log(e.target.getExtData());
	    	licenseML.markerList.render(e.target.getExtData());
	    },
	    
		/** 
		 * 添加自定义标注 
		 */  
		createCustomMarker: function(data, divNumber){    
			/** 
		     * 自定义覆盖物dom元素   
		     */ 
		    var div = document.createElement("div");    
		    div.id = 'div'+divNumber;  
		    div.style.width = "76px";  
		    div.style.height = "76px";  
		    divNumber++;  
		      
		    var marker = new AMap.Marker({    
		        map:gis.map,
		        position:new AMap.LngLat(data.longitude, data.latitude), //基点位置    
		        offset: new AMap.Pixel(-5, 5),
		        //draggable:true,  //是否可拖动    
		        content:div   //自定义覆盖物内容    
		    });  
		    
		    if(!licenseML.inited && licenseML.cityDataLength>licenseML.cityMarker.length){
		    	licenseML.cityMarker.push(marker);
		    }
		    if(licenseML.cityDataLength == licenseML.cityMarker.length){
		    	licenseML.inited = true;
		    }
		    marker.setExtData(data.sublist);
		    AMap.event.addListener(marker, 'click', licenseML._onClick);
		    
		    gis.map.getContainer().appendChild(div); //这句代码是关键,就是添加一个可引用的div,否则在echarts做图时会抛出找不多div节点的错误
		    licenseML.createPie(div.id,data);
	        return marker;
		},
		
		 /** 
	     * 添加饼图 
	     */  
		createPie: function(divId, data) {
		    // 基于准备好的dom，初始化echarts图表
	        var myChart = echarts.init(document.getElementById(divId)); 
	        
	        var option = {
	    	    tooltip : {
	    	        trigger: 'item',
	    	        formatter: "{a} <br/>{b} : {c} ({d}%)",
	    	        backgroundColor:'#fff',
	    	        textStyle: {
	    	        	color: '#333'
	    	        }
	    	    },
	    	    series : [
	    	        {
	    	            name: '许可证到期预警数量',
	    	            type: 'pie',
	    	            radius : '70%',
	    	            center: ['50%', '50%'],
	    	            data:[
	    	                {value:data.pastDueNum, name:'超期', itemStyle: {normal: {color: '#613762'}} },
	    	                {value:data.onePastDueNum, name:'1个月内', itemStyle: {normal: {color: '#B62C2F'}} },
	    	                {value:data.twoPastDueNum, name:'2个月内', itemStyle: {normal: {color: '#EF2D06'}} },
	    	                {value:data.threePastDueNum, name:'3个月内', itemStyle: {normal: {color: '#FF7371'}} },
	    	                {value:data.sixPastDueNum, name:'6个月内', itemStyle: {normal: {color: '#FF9022'}} },
	    	                {value:data.gtSixPastDueNum, name:'6个月以上', itemStyle: {normal: {color: '#59B136'}} }
	    	            ],
	    	            itemStyle: {
	    	                emphasis: {
	    	                    shadowBlur: 10,
	    	                    shadowOffsetX: 0,
	    	                    shadowColor: 'rgba(0, 0, 0, 0.5)'
	    	                },
	    	                normal: {
	    	                    label:{show:false}
	    	                }
	    	            }
	    	        }
	    	    ]
	    	};

	        // 为echarts对象加载数据 
	        myChart.setOption(option); 
		}
	};
	
	return licenseML;
});